import {Injectable} from '@angular/core';
import {HttpClient, HttpHandler, HttpInterceptor, HttpRequest, HttpEvent, HttpResponse, HttpParams,
  HttpHeaders } from '@angular/common/http';
import {PubSubService} from '../pub-sub/pub-sub.service';
import {SKey, StorageService} from './storage.service';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/shareReplay';
import {urlServer} from '../share-data';


export class MyResponse {
  constructor(
    public success: boolean,
    public code = '',
    public message: string,
    public data: any,
  ) {}
}

@Injectable()
export class HttpClientService {
  constructor(
    private http: HttpClient,
    private pubSub: PubSubService,
    private session: StorageService
  ) {
  }

  /**
   * 返回一个obj 对象
   * @param url
   * @param urlSearchParams url 的查询参数
   * @returns {Observable<{}>}
   */
  // apiGet(url, urlSearchParams?: any): Observable<{}> {
  //   const options = {
  //     params: urlSearchParams,
  //     responseType: 'json'
  //   };
  //   return this.http.request(Service.METHOD_GET, url, options);
  // }

  get(url: string, params?: HttpParams): Observable<MyResponse> {
    const urlNew = urlServer + url;
    const options = {headers: this.getHttpHeaders(), params: params};
    // this.http.get(urlNew, options)
    //   .pipe()
    //   .do()
    //   .
    return this.http
      .get<MyResponse>(urlNew, options)
      .do(res => {
        if (!res.success) {
          this.pubSub.msgChange.error(res.message);
        }
        return res;
      }, error => {
        // here we can show an error message to the user,
        // for example via a service
        console.error('error catched', error);

        return Observable.create({description: 'Error Value Emitted'});
      })
      .shareReplay();
    // return this.http.get(url,null)
    //   .map(res=>res.join())
    //   .map(res=>res as MyResponse)
  }

  getFile(url: string) {
    return this.http
      .get(url, {observe: 'response'})
      .do(data => {
        return { success: true, code: data.status, data: data.body };
      }, error => {
        console.error('error catched', error);
        this.pubSub.msgChange.error(error.message);
        return Observable.create({description: 'Error Value Emitted'});
      })
      .shareReplay();
  }

  post(url: string, body: any, params?: HttpParams): Observable<MyResponse> {
    const urlNew = urlServer + url;
    const options = {headers: this.getHttpHeaders(), params: params};
    return this.http.post<MyResponse>(urlNew, body, options)
      .do(res => {
        if (res == null || !res.success) {
          if (res == null) {
            this.pubSub.msgChange.error(`res为null,后台运行出错。`);
          } else {
            this.pubSub.msgChange.error(res.message);
          }
        }
        return res;
      }, error => {
        console.error('error catched', error);
        return Observable.create({description: 'Error Value Emitted'});
      })
      .shareReplay();
  }

  delete(url: string, params?: HttpParams): Observable<MyResponse> {
    const urlNew = urlServer + url;
    const options = {headers: this.getHttpHeaders(), params: params};
    return this.http
      .delete<MyResponse>(urlNew, options)
      .do(res => {
        if (!res.success) {
          this.pubSub.msgChange.error(res.message);
        }
        return res;
      }, error => {
      console.error('error catched', error);
      return Observable.create({description: 'Error Value Emitted'});
    }).shareReplay();
  }

  download(url?: string): Observable<any> {
    const header = new HttpHeaders()
      .set('Authorization', 'Bearer ' + this.session.token);
    // header.append('Authorization', 'Bearer ' + this.session.token)
    const options = { headers: header, responseType: 3};
    const body = {};
    return this.http.post(url, null, { headers: header, responseType: 'arraybuffer'})
      .do(res => {
        const blob = new Blob([res], {type: 'application/vnd.ms-excel'});
        const objectUrl = URL.createObjectURL(blob);
        // var aForExcel = $('<a><span class='forExcel'>下载excel</span></a>').attr('href',objectUrl);
        // $('body').append(aForExcel);
        // $('.forExcel').click();
        // aForExcel.remove();
        return res;
      }, error => {
        // here we can show an error message to the user,
        // for example via a service
        console.error('error catched', error);

        return Observable.create({description: 'Error Value Emitted'});
      });
  }

  getHttpHeaders() {
    if (this.session.has(SKey[SKey.TokenData])) {
      return new HttpHeaders()
        .set('Accept', 'application/json')
        .set('Content-Type', 'application/json')
        .set('Access-Control-Allow-Origin', '*')
        .set('Authorization', 'Bearer ' + this.session.token);
    } else {
      return  new HttpHeaders()
        .set('Accept', 'application/json')
        .set('Content-Type', 'application/json')
        .set('Access-Control-Allow-Origin', '*');
    }
  }
}

@Injectable()
export class NoopInterceptor implements HttpInterceptor {
  constructor(
  ) {}
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req);
  }


}
